package com.lngsyz.eseal.base.biz.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lngsyz.eseal.base.entity.source1.TFile;
import com.lngsyz.eseal.base.exception.RequestSystemException;
import com.lngsyz.eseal.base.mapper.source1.TFileMapper;
import com.lngsyz.eseal.base.util.CommonUtil;
import com.lngsyz.eseal.base.util.StringUtil;

@Service
public class TFileService {
    
	@Autowired
	TFileMapper tFileMapper;
	
	public TFile addFile(MultipartFile file) throws Exception {
		TFile tFile = packageEntity(file);
		saveFile(file, tFile.getLocalPath(), tFile.getLocalName());
		insert(tFile);
		return tFile;
	}

	private void insert(TFile tFile) throws Exception {
		if(tFile != null) {
			tFileMapper.insert(tFile);
		} else {
			throw new RequestSystemException("文件处理异常，无法保存");
		}
    }
	
	private TFile packageEntity(MultipartFile file) {
		TFile rtn = new TFile();
		rtn.setId(CommonUtil.createUuid());
		// 原始文件名字
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		// 文件路径
		// 本地服务器文件绝对路径[D:/img/]
		String serverPath = StringUtil.getConfiguration("config.properties", "IMAGE_LOCAL_PATH");
		// [/img]
		String relativePath = StringUtil.getConfiguration("config.properties", "IMAGE_NET_PATH");
		// 文件夹
		String folderName = "/" + getDateFolder();
		rtn.setNetFolder(relativePath + folderName);
		rtn.setNetName(fileName);
		rtn.setLocalName(CommonUtil.createUuid() + "." + suffix);
		rtn.setLocalPath(serverPath + folderName);
		return rtn;
	}
	
	private void saveFile(MultipartFile file, String imageFolder, String imageName) throws Exception {
		CommonUtil.saveFile(file, imageFolder, imageName);
	}
	
	private String getDateFolder() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
	}
	
	public TFile getFile(String imgId){
		return tFileMapper.findById(imgId);
	}
}
